package com.cqc.itemtouchhelper01;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private Context context;
    private RecyclerView recyclerView;
    private List<String> datas = new ArrayList<>();
    private Toast toast;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        toast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
        initData();
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new DividerItemDecoration(context, LinearLayoutManager.VERTICAL));
        final MyAdapter adapter = new MyAdapter(datas);
        recyclerView.setAdapter(adapter);

        adapter.setOnItemClickListener(new MyAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                toast.setText(position+"");
                toast.show();
            }
        });
//
        RecyclerViewCallBack callBack = new RecyclerViewCallBack(new RecyclerViewCallBack.ItemTouchHelperCallback() {
            @Override
            public void onItemDelete(int position) {
                //没有动画效果
                datas.remove(position);
                adapter.notifyDataSetChanged();

                //有动画效果,但是点击position后面的item，仍然显示之前的position，除非将这个划出屏幕在划回来
//                datas.remove(position);
//                adapter.notifyItemRemoved(position);
            }

            @Override
            public void onMove(int fromPosition, int toPosition) {
                Collections.swap(datas, fromPosition, toPosition);
                adapter.notifyItemMoved(fromPosition,toPosition);
//                adapter.notifyDataSetChanged();
            }
        });
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callBack);
        itemTouchHelper.attachToRecyclerView(recyclerView);

    }

    private void initData() {
        for (int i = 0; i < 100; i++) {
            datas.add("item" + i);
        }
    }
}
